package com.jarchie.newfuncdemo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by Jarchie on 2018\3\5.
 * 自定义电子签名组件
 */

public class SignView extends View {

    private Paint linePaint; //画笔
    private ArrayList<Path> lines; //写字的笔迹，支持多笔画
    private int lineCount; //记录笔画数目
    private final int DEFAULT_LINE_WIDTH = 10; //默认画笔的宽度
    private int lineColor = Color.BLACK; //默认字迹的颜色
    private float lineWidth = DEFAULT_LINE_WIDTH; //笔画宽度

    public SignView(Context context) {
        super(context);
        initLinePaint();
        lines = new ArrayList<>();
    }

    public SignView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SignView);
            parseTypedArray(typedArray);
        }
        initLinePaint();
        lines = new ArrayList<>();
    }

    public SignView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SignView);
            parseTypedArray(typedArray);
        }
        initLinePaint();
        lines = new ArrayList<>();
    }

    @SuppressLint("NewApi")
    public SignView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SignView, defStyleAttr, defStyleRes);
            parseTypedArray(typedArray);
        }
        initLinePaint();
        lines = new ArrayList<>();
    }

    //初始化画笔
    private void initLinePaint() {
        linePaint = new Paint();
        linePaint.setColor(lineColor);
        linePaint.setStrokeWidth(lineWidth);
        linePaint.setStrokeCap(Paint.Cap.ROUND);
        linePaint.setPathEffect(new CornerPathEffect(50));
        linePaint.setStyle(Paint.Style.STROKE);
    }

    //接收输入信息
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: //按下屏幕
                Path path = new Path();
                path.moveTo(event.getX(), event.getY());
                lines.add(path);
                lineCount = lines.size();
                break;
            case MotionEvent.ACTION_MOVE: //在屏幕上移动
                lines.get(lineCount - 1).lineTo(event.getX(), event.getY());
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return true;
    }

    //显示输入信息
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (lines != null && lines.size() > 0) {
            for (Path path : lines) {
                canvas.drawPath(path, linePaint);
            }
        }
    }

    //设置线的颜色
    public void setLineColor(int lineColor) {
        this.lineColor = lineColor;
        linePaint.setColor(lineColor);
    }

    //设置线宽
    public void setLineWidth(float lineWidth) {
        this.lineWidth = lineWidth;
        linePaint.setStrokeWidth(lineWidth);
    }

    //解析类型数组
    private void parseTypedArray(TypedArray typedArray) {
        lineColor = typedArray.getColor(R.styleable.SignView_lineColor, Color.BLACK);
        lineWidth = typedArray.getDimension(R.styleable.SignView_lineWidth, DEFAULT_LINE_WIDTH);
    }

    //清空输入
    public void clearPath() {
        lines.removeAll(lines);
        invalidate();
    }

    //保存view视图的Bitmap信息
    public Bitmap getImage(){
        Bitmap bitmap = Bitmap.createBitmap(getWidth(),getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //绘制背景
        Drawable bgDrawable = getBackground();
        if (bgDrawable != null)
            bgDrawable.draw(canvas);
        else
            canvas.drawColor(Color.WHITE);
        draw(canvas); //绘制View视图的内容
        return bitmap;
    }

    //将图像保存到文件
    public boolean saveImageToFile(String filePath){
        try {
            File file = new File(filePath);
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            getImage().compress(Bitmap.CompressFormat.PNG,100,fos);
            fos.flush();
            fos.close();
            return true;
        }catch (FileNotFoundException e){
            return false;
        }catch (IOException e){
            return false;
        }
    }

}
